﻿/***************
 * 调用安卓原生接口进行音乐播放
 * 需将音频文件放到StreamingAssets目录
 * 
 * 
 * 
 * *********************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AndroidSoundTool : MonoSingleton<AndroidSoundTool>
{
    private AndroidJavaClass unityActivityClass;
    private AndroidJavaObject activityObj;
    private AndroidJavaObject soundObj;

    private Dictionary<string, int> _soundMap = new Dictionary<string, int>();

    public override void Initialize()
    {
        unityActivityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        activityObj = unityActivityClass.GetStatic<AndroidJavaObject>("currentActivity");
        soundObj = new AndroidJavaObject("com.plugins.unity.vibrator.AudioCenter", 10, activityObj);
    }


    public void LoadSound(List<string> soundName, string typeStr = "mp3")
    {
        for (int i = 0; i < soundName.Count; i++)
        {
            LoadSound(soundName[i], typeStr);
        }
    }
    /// <summary>
    /// 加载音效
    /// 需要带后缀：***.mp3
    /// </summary>
    /// <param name="soundName"></param>
    /// <returns></returns>
    public int LoadSound(string soundName,string typeStr ="mp3")
    {
        int id;
        if (!_soundMap.ContainsKey(soundName))
        {
            id = soundObj.Call<int>("loadSound", new object[] { string.Format("{0}.{1}", soundName, typeStr) });
            _soundMap.Add(soundName, id);
        }
        else {
            return _soundMap[soundName];
        }
        return id;
    }

    public void PlaySound(string soundName,int priority = 1)
    {
        if (!SoundManager.Instance.SoundOn)
        {
            return;
        }
        PlaySound(_soundMap[soundName]);
    }

    private void PlaySound(int soundId, float volume = 1, int priority = 1)
    {
        soundObj.Call("playSound", new object[] { soundId, volume, priority });
    }

    public int GetSoundId(string name)
    {
        if (_soundMap.ContainsKey(name))
        {
            return _soundMap[name];
        }
        return -1;
    }

    public void UnloadSound(string name)
    {
        if (_soundMap.ContainsKey(name))
        {
            int id = _soundMap[name];
            UnloadSound(id);
        }
    }

    public void UnloadSound(int soundId)
    {
        soundObj.Call("unloadSound", new object[] { soundId });
    }
}
